package com.haoyu.demo;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.realm.SimpleAccountRealm;
import org.apache.shiro.subject.Subject;
import org.junit.Before;
import org.junit.Test;

/**
 * @author: 蒿雨
 * @create: 2022-01-06 15:21
 * @description:测试12123
 */
public class AuthenticationTest {

    SimpleAccountRealm simpleAccountRealm = new SimpleAccountRealm();

    // 在方法开始前添加一个用户,让它具备admin和user两个角色
    @Before
    public void addUser(){
        simpleAccountRealm.addAccount("lkk","123");
    }

    @Test
    public void testAuthentication(){
        //1、构建SecurityManager的环境
        DefaultSecurityManager defaultSecurityManager=new DefaultSecurityManager();
        defaultSecurityManager.setRealm(simpleAccountRealm);

        //2、主体提交认证请求
        // 设置SecurityManager环境
        SecurityUtils.setSecurityManager(defaultSecurityManager);
        // 获取当前主体
        Subject subject = SecurityUtils.getSubject();

        //登录
        UsernamePasswordToken token = new UsernamePasswordToken("lkk","123");
        subject.login(token);

        // subject.isAuthenticated()方法返回一个boolean值,用于判断用户是否认证成功
        System.out.println("isAuthenticated:"+subject.isAuthenticated());

        //登出
        subject.logout();

        System.out.println("isAuthenticated:"+subject.isAuthenticated());

    }


}
